package com.entfrm.auth.filter;

import cn.hutool.core.util.StrUtil;
import com.entfrm.auth.exception.ValidateCodeException;
import com.entfrm.auth.service.ValidateCodeService;
import com.entfrm.core.auth.properties.ValidateCodeProperties;
import com.entfrm.core.auth.util.AuthUtil;
import com.entfrm.core.base.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author entfrm
 * @date 2018/11/21
 */
@Slf4j
@AllArgsConstructor
@Component("validateCodeFilter")
@EnableConfigurationProperties(ValidateCodeProperties.class)
public class ValidateCodeFilter extends OncePerRequestFilter {

    private final ValidateCodeService validateCodeService;

    private final ValidateCodeProperties validateCodeProperties;

    private final ObjectMapper objectMapper;

    /**
     * 返回true代表不执行过滤器，false代表执行
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        //登录提交的时候验证验证码
        if (StrUtil.containsAny(request.getRequestURI(), "/auth/user/token")) {
            //判断是否有不验证验证码的client
            if (validateCodeProperties.getIgnoreClientCode().length > 0) {
                try {
                    final String[] clientInfos = AuthUtil.extractClient(request);
                    String clientId = clientInfos[0];
                    for (String client : validateCodeProperties.getIgnoreClientCode()) {
                        if (client.equals(clientId)) {
                            return true;
                        }
                    }
                } catch (Exception e) {
                    log.error("解析client信息失败", e);
                }
            }
            return false;
        }
        return true;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            validateCodeService.validate(request);
        } catch (ValidateCodeException e) {
            ResponseUtil.responseWriter(objectMapper, response, e.getMessage(), HttpStatus.BAD_REQUEST.value());
            return;
        }
        chain.doFilter(request, response);
    }
}
